
from django.contrib.auth.decorators import permission_required
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.

from .. import models
from django.core.urlresolvers import reverse
import os
from . viewsindex import uploads
from web.settings import BASE_DIR



@permission_required('myadmin.insert_goods',raise_exception = True)
# 商品添加页面

def goodsadd(request):
    # 获取所有的商品
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    context = {'cateslist':data}
    return render(request,'myadmin/goods/add.html',context)


@permission_required('myadmin.insert_goods',raise_exception = True)
# 商品执行添加
def goodsinsert(request):
    try:
        # 接收数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        # print(data)
        # {'cateid': '9', 'price': '2999.999', 'info': '<p>vivoX6plus&nbsp; lalalalaal</p>', 'store': '23', 'title': 'vivoX6plus '}
        data['cateid'] = models.Cates.objects.get(id=data['cateid'])

        # 处理上传的商品主图
        myfile = request.FILES.get('pic_url')
        if myfile:
            data['pic_url'] = uploads(myfile)
        else:
            return HttpResponse('<script>alert("必须上传商品主图");history.back(-1);</script>')


        # 执行数据添加
        ob = models.Goods(**data)
        ob.save()
        return HttpResponse('<script>alert("添加成功～～～");location.href="'+reverse('myadmin_goodsindex')+'"</script>')
        # 商品的外键添加一个分类对象
    except:
        return HttpResponse('<script>alert("添加失败～～～");location.href="'+reverse('myadmin_goodsadd')+'"</script>')


@permission_required('myadmin.show_goods',raise_exception = True)
# 商品列表
def goodsindex(request):
    # 获取所有数据
    obs = models.Goods.objects.all()


    # 获取搜索类别和关键字
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断是否有搜索类型
        if types == 'title':
            obs = obs.filter(title__contains=keywords)
        elif types == 'status':
            arr = {'新品':0,'热卖':1,'下架':2}
            obs = obs.filter(status=arr[keywords])
        elif types == 'price':
            # 切分关键字，
            
            # 获取价格区间
            arr = keywords.split(',')
            obs = obs.filter(price__gte=arr[0]).filter(price__lte=arr[1])
            # print(obs)
        elif types == 'store':
            arr = keywords.split(',')
            obs = obs.filter(store__gte=arr[0]).filter(store__lte=arr[1])
        elif types == 'cilcknum':
            arr = keywords.split(',')
            obs = obs.filter(cilcknum__gte=arr[0]).filter(cilcknum__lte=arr[1])
        elif types == 'ordernum':
            arr = keywords.split(',')
            obs = obs.filter(ordernum__gte=arr[0]).filter(ordernum__lte=arr[1])


     # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
    paginator = Paginator(obs,10)

    # 获取当前页码数  ?p=n
    p = request.GET.get('p',1)
    # 获取当前页的数据
    goodslist = paginator.page(p)

    # 分配数据
    context = {'goodslist':goodslist}
    # 加载模板
    return render(request,'myadmin/goods/index.html',context)


@permission_required('myadmin.del_goods',raise_exception = True)
# 商品删除
def goodsdel(request,uid):
    try:
        # 根据uid获取用户对象,修改状态
        ob = models.Goods.objects.get(id=uid)
        ob.status = 2
        ob.save()

        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_goodsindex')+'"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_goodsindex')+'"</script>')





@permission_required('myadmin.edit_goods',raise_exception = True)
# 商品修改

def goodsedit(request,uid):

    # 根据　uid 获取商品对象
    ob = models.Goods.objects.get(id=uid)
    # 判断请求方式
    if request.method == 'GET':
        # 获取所有的商品分类数据
        cateslist = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        # 显示编辑的表单
        return render(request,'myadmin/goods/edit.html',{'goodsinfo':ob,'cateslist':cateslist})

    elif request.method == 'POST':
        try:
            # print(request.POST.dict())
            # 执行编辑
            ob.cateid = models.Cates.objects.get(id=request.POST.get('cateid'))
            ob.title = request.POST.get('title')
            ob.pirce = request.POST.get('price')
            ob.store = request.POST.get('store')
            ob.status = request.POST.get('status')
            ob.info = request.POST.get('info')
            # 判断是否更新了商品主图
            myfile = request.FILES.get('pic_url')
            if myfile:
                #  # 如果修改了头像,要上传新的头像,并判断是否删除以前头像
                # if ob.pic_url != '/static/pics/users.jpg':
                try:
                    # 删除原来上传的头像
                    os.remove(BASE_DIR+ob.pic_url)
                except:
                    pass
                # 更新头像
                ob.pic_url = uploads(myfile)

            ob.save()

            return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_goodsindex')+'"</script>')
        except:
            return HttpResponse('<script>alert("修改失败");history.back(-1);</script>')

        
